﻿using Domain.Entity;
using DtoFw.Query;
using Repository.Base;
using System;
using System.Collections.Generic;
using System.Text;
using Util;
using System.Linq;

namespace Repository
{
    public class CaseAttachFileRepository : BaseRepository<CaseAttachFileEntity>
    {
        public readonly CaseAttachFileEvidenceRepository eviRef;
        private readonly SnowFlakeGenerator worker;
        public CaseAttachFileRepository(SnowFlakeGenerator snowFlakeGenerator) : base(snowFlakeGenerator)
        {
            this.worker = snowFlakeGenerator;
            this.eviRef = new CaseAttachFileEvidenceRepository(snowFlakeGenerator);
        }

        public List<CaseAttachFileEntity> QueryList(CaseAttachReqDto query, ref int total)
        {
            string sql = @"SELECT s1.*
                             FROM case_attachfile s1  
                            where s1.isdeleted=0 AND s1.caseid=" + query.caseid;
            if (!string.IsNullOrEmpty(query.evidenceId))
            {
                if (query.exclude == "y")
                    sql += $" And not exists(select * from case_attachfile_evidence t1 where t1.attachId=s1.id and t1.IsDeleted=0 and t1.evidenceId=" + query.evidenceId + ")";
                else
                    sql += $" And exists(select * from case_attachfile_evidence t1 where t1.attachId=s1.id and t1.IsDeleted=0 and t1.evidenceId=" + query.evidenceId + ")";
            }
            var ls1 = this.GetDb().SqlQueryable<CaseAttachFileEntity>(sql).ToPageList(query.Page, query.PageSize, ref total);
            if (ls1 != null && ls1.Count > 0)
            {
                var ls2 = this.eviRef.QueryCaseAttachfileEvidence(ls1.Select(v => v.Id).ToArray());
                foreach (var item in ls1)
                {
                    var ls3 = ls2.Where(v => v.attachId == item.Id);
                    item.EviName = string.Join("、", ls3.Select(v => v.Name));
                    item.EviNo = string.Join("、", ls3.Select(v => v.No));
                }
            }
            return ls1;
        }

       
    }

    public class CaseAttachFileEvidenceRepository : BaseRepository<CaseAttachFileEvidenceEntity>
    {
        private readonly SnowFlakeGenerator worker;
        public CaseAttachFileEvidenceRepository(SnowFlakeGenerator snowFlakeGenerator) : base(snowFlakeGenerator)
        {
            this.worker = snowFlakeGenerator;
        }

        public List<dynamic> QueryCaseAttachfileEvidence(long[] ids)
        {
            string sql = $@"select s1.attachId,s2.`Name`,s2.`No` 
                              from case_attachfile_evidence s1
                              join case_physical_evidence s2 on s1.evidenceId=s2.Id
                             where s1.IsDeleted=0
                               and s1.attachId in({string.Join(",", ids)})";
            return this.GetDb().SqlQueryable<dynamic>(sql).ToList();
        }

    }
}
